package com.ruoyi.system.basicInformation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.basicInformation.service.ITTerminalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.ruoyi.system.basicInformation.bo.TCarAddBo;
import com.ruoyi.system.basicInformation.bo.TCarQueryBo;
import com.ruoyi.system.basicInformation.bo.TCarEditBo;
import com.ruoyi.system.basicInformation.domain.TCar;
import com.ruoyi.system.basicInformation.mapper.TCarMapper;
import com.ruoyi.system.basicInformation.vo.TCarVo;
import com.ruoyi.system.basicInformation.service.ITCarService;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 车辆信息Service业务层处理
 *
 * @author ruoyi
 * @date 2021-05-18
 */
@Service
public class TCarServiceImpl extends ServiceImpl<TCarMapper, TCar> implements ITCarService {

    @Autowired
    private ITTerminalService terminalService;

    @Override
    public TCarVo queryById(Long id) {
        return this.baseMapper.selectById(id);
    }

    @Override
    public List<TCarVo> queryList(TCarQueryBo bo) {
//        LambdaQueryWrapper<TCar> lqw = Wrappers.lambdaQuery();
//        lqw.eq(StrUtil.isNotBlank(bo.getLicensePlate()), TCar::getLicensePlate, bo.getLicensePlate());
//        lqw.eq(StrUtil.isNotBlank(bo.getModel()), TCar::getModel, bo.getModel());
//        lqw.eq(StrUtil.isNotBlank(bo.getEngineNumber()), TCar::getEngineNumber, bo.getEngineNumber());
//        lqw.eq(StrUtil.isNotBlank(bo.getChassisNumber()), TCar::getChassisNumber, bo.getChassisNumber());
//        lqw.eq(StrUtil.isNotBlank(bo.getCadre()), TCar::getCadre, bo.getCadre());
//        lqw.eq(StrUtil.isNotBlank(bo.getContact()), TCar::getContact, bo.getContact());
//        lqw.eq(StrUtil.isNotBlank(bo.getType()), TCar::getType, bo.getType());
//        lqw.eq(StrUtil.isNotBlank(bo.getServiceLife()), TCar::getServiceLife, bo.getServiceLife());
//        lqw.eq(bo.getUseDeadline() != null, TCar::getUseDeadline, bo.getUseDeadline());
//        lqw.eq(bo.getCreateById() != null, TCar::getCreateById, bo.getCreateById());
//        lqw.eq(bo.getUpdateById() != null, TCar::getUpdateById, bo.getUpdateById());
//        return entity2Vo(this.list(lqw));
        if (SecurityUtils.getLoginUser().getUser().getAreaId() != 1)
            bo.setAreaId(SecurityUtils.getLoginUser().getUser().getAreaId() > 0 ? SecurityUtils.getLoginUser().getUser().getAreaId() : 0);
        return this.baseMapper.selectDTO(bo);
    }


    @Override
    public List<TCarVo> listCarCurrentPoint(TCarQueryBo bo) {
        if (SecurityUtils.getLoginUser().getUser().getAreaId() != 1)
            bo.setAreaId(SecurityUtils.getLoginUser().getUser().getAreaId() > 0 ? SecurityUtils.getLoginUser().getUser().getAreaId() : 0);
        return this.baseMapper.listCarCurrentPoint(bo);
    }

    @Override
    public Boolean checkCarLimit() {
        return this.baseMapper.checkCarLimit() > 0;
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<TCarVo> entity2Vo(Collection<TCar> collection) {
        List<TCarVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, TCarVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<TCar> page = (Page<TCar>) collection;
            Page<TCarVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(TCarAddBo bo) {
        TCar add = BeanUtil.toBean(bo, TCar.class);
        validEntityBeforeSave(add, 1);
        Boolean result = this.save(add);
        terminalService.updateTerminalByObjId(bo.getTerminalId(), add.getId());
        //bo = BeanUtil.toBean(add, TCarAddBo.class);
        return result;
    }

    @Override
    public Boolean updateByEditBo(TCarEditBo bo) {
        TCar update = BeanUtil.toBean(bo, TCar.class);
        validEntityBeforeSave(update, 2);
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(TCar entity, int type) {
        //TODO 做一些数据校验,如唯一约束
        QueryWrapper<TCar> lqw = new QueryWrapper<>();
        lqw.lambda().eq(TCar::getLicensePlate, entity.getLicensePlate());
        TCar tShip = this.baseMapper.selectOne(lqw);
        if (Validator.isNotNull(tShip)) {
            //type为1时为新增
            if (type == 1) {
                //TODO 做一些数据校验,如唯一约束
                throw new BaseException("此车牌号码已存在！");
            } else {
                if (entity.getId().longValue() != tShip.getId().longValue()) {
                    //TODO 做一些数据校验,如唯一约束
                    throw new BaseException("此车牌号码已存在！");
                }
            }
        }

        QueryWrapper<TCar> lqw1 = new QueryWrapper<>();
        lqw1.lambda().eq(TCar::getEngineNumber, entity.getEngineNumber());
        TCar tShip1 = this.baseMapper.selectOne(lqw1);
        if (Validator.isNotNull(tShip1)) {
            //type为1时为新增
            if (type == 1) {
                //TODO 做一些数据校验,如唯一约束
                throw new BaseException("此发动机号码已存在！");
            } else {
                if (entity.getId().longValue() != tShip1.getId().longValue()) {
                    //TODO 做一些数据校验,如唯一约束
                    throw new BaseException("此发动机号码已存在！");
                }
            }
        }
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }
}
